package cn.amos.web.controller;

import cn.amos.core.business.ProductBusiness;
import cn.amos.dao.entity.ProductEntity;
import cn.amos.facade.request.ProductForm;
import cn.amos.web.request.ProductRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 产品相关API
 * @author DaoyuanWang
 */
@RequestMapping(value = "product")
@Controller
public class ProductController {

    @Resource
    private ProductBusiness productBusiness;

    /**
     * 跳转到产品输入页面
     */
    @RequestMapping(value = "input.do",method = RequestMethod.POST)
    public String inputProduct() {
        return "back/ProductPage";
    }

    /**
     * 产品信息输入后保存产品信息到数据库
     */
    @RequestMapping(value = "save.do", method = RequestMethod.POST)
    public String saveProduct(ProductRequest productRequest, Model model) {
        ProductForm productForm = new ProductForm();
        BeanUtils.copyProperties(productRequest,productForm);

        productBusiness.addOne(productForm);

        model.addAttribute("product", productRequest);
        return "back/ProductPage";
    }

    /**
     * 获得所有产品信息
     */
    @RequestMapping(value = "getAll.do")
    @ResponseBody
    public void getProductAll(HttpServletResponse response) {

        // 彻底解决中文乱码
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        // 遍历出所有数据
        List<ProductEntity> list = productBusiness.getProductAll();

        // 定义一个可变 StringBuffer 并加入数据
        StringBuilder str = new StringBuilder();
        for (ProductEntity product : list) {
            str.append(product);
            str.append("<br>");
        }

        // 将整个 StringBuffer 输出至网页
        try {
            response.getWriter().write(str.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
